
<template>
  <div
      ref="containerRef"
      class="virtual-scroller"
      :style="{ height: `${containerHeight}px` }"
      @scroll="handleScroll"
  >
    <!-- 占位元素，撑开完整列表高度 -->
    <div
        class="virtual-scroller__placeholder"
        :style="{ height: `${totalHeight}px` }"
    />

    <!-- 可见内容区域 -->
    <div
        class="virtual-scroller__content"
        :style="{ transform: `translateY(${offsetY}px)` }"
    >
      <div
          v-for="item in visibleItems"
          :key="getItemKey(item)"
          class="virtual-scroller__item"
          :style="getItemStyle(item)"
          @click="emit('itemClick', item)"
      >
        <slot name="item" :item="item" :index="getItemIndex(item)">
          <div class="virtual-scroller__item-default">
            {{ item.content }}
          </div>
        </slot>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="virtual-scroller__loading">
      <div class="loading-spinner"></div>
      <span>加载中...</span>
    </div>

    <!-- 空状态 -->
    <div v-if="!loading && items.length === 0" class="virtual-scroller__empty">
      <div class="empty-icon">📄</div>
      <span>暂无数据</span>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  watch,
  onMounted,
  onUnmounted,
  nextTick
} from 'vue'

// 组件属性
const props = defineProps({
  items: {
    type: Array,
    required: true,
    default: () => []
  },
  containerHeight: {
    type: Number,
    default: 400
  },
  itemHeight: {
    type: Number,
    default: 50
  },
  buffer: {
    type: Number,
    default: 5
  },
  keyField: {
    type: String,
    default: 'id'
  },
  loading: {
    type: Boolean,
    default: false
  },
  dynamicHeight: {
    type: Boolean,
    default: false
  }
})

// 事件定义
const emit = defineEmits(['itemClick', 'scroll', 'visibleChange'])

// 响应式状态
const containerRef = ref(null)
const scrollTop = ref(0)
const itemHeights = ref({})
const measuredItems = ref(new Set())

// 计算可见范围
const visibleRange = computed(() => {
  if (props.items.length === 0) {
    return { startIndex: 0, endIndex: 0 }
  }

  let startIndex = 0
  let currentHeight = 0

  // 动态高度计算起始索引
  if (props.dynamicHeight) {
    for (let i = 0; i < props.items.length; i++) {
      const itemHeight = getDynamicItemHeight(props.items[i])
      if (currentHeight + itemHeight > scrollTop.value) {
        startIndex = Math.max(0, i - props.buffer)
        break
      }
      currentHeight += itemHeight
    }
  } else {
    // 固定高度计算
    startIndex = Math.floor(scrollTop.value / props.itemHeight)
    startIndex = Math.max(0, startIndex - props.buffer)
  }

  // 计算结束索引
  let visibleHeight = 0
  let endIndex = startIndex

  for (let i = startIndex; i < props.items.length; i++) {
    const itemHeight = props.dynamicHeight ? getDynamicItemHeight(props.items[i]) : props.itemHeight
    visibleHeight += itemHeight
    endIndex = i + 1

    if (visibleHeight > props.containerHeight + scrollTop.value + props.buffer * props.itemHeight) {
      break
    }
  }

  endIndex = Math.min(props.items.length, endIndex + props.buffer)

  return { startIndex, endIndex }
})

// 可见项目
const visibleItems = computed(() => {
  return props.items.slice(visibleRange.value.startIndex, visibleRange.value.endIndex)
})

// 总高度计算
const totalHeight = computed(() => {
  if (props.dynamicHeight) {
    return props.items.reduce((total, item) => {
      return total + getDynamicItemHeight(item)
    }, 0)
  }
  return props.items.length * props.itemHeight
})

// Y轴偏移量
const offsetY = computed(() => {
  if (props.dynamicHeight) {
    let offset = 0
    for (let i = 0; i < visibleRange.value.startIndex; i++) {
      offset += getDynamicItemHeight(props.items[i])
    }
    return offset
  }
  return visibleRange.value.startIndex * props.itemHeight
})

// 获取动态项目高度
const getDynamicItemHeight = (item) => {
  const key = getItemKey(item)
  return itemHeights.value[key] || props.itemHeight
}

// 获取项目键值
const getItemKey = (item) => {
  return item[props.keyField] || JSON.stringify(item)
}

// 获取项目索引
const getItemIndex = (item) => {
  return props.items.findIndex(i => getItemKey(i) === getItemKey(item))
}

// 获取项目样式
const getItemStyle = (item) => {
  const baseStyle = {
    height: props.dynamicHeight ? 'auto' : `${props.itemHeight}px`,
    minHeight: `${props.itemHeight}px`
  }

  if (props.dynamicHeight) {
    const key = getItemKey(item)
    if (itemHeights.value[key]) {
      baseStyle.height = `${itemHeights.value[key]}px`
    }
  }

  return baseStyle
}

// 滚动处理
const handleScroll = (event) => {
  console.info(event)
  scrollTop.value = event.target.scrollTop
  emit('scroll', {
    scrollTop: scrollTop.value,
    scrollLeft: event.target.scrollLeft,
    event
  })
}

// 测量项目高度
const measureItemHeight = (item, element) => {
  if (!props.dynamicHeight || !element) return

  const key = getItemKey(item)
  if (measuredItems.value.has(key)) return

  nextTick(() => {
    const height = element.getBoundingClientRect().height
    if (height && height !== props.itemHeight) {
      itemHeights.value[key] = height
      measuredItems.value.add(key)
    }
  })
}

// 监听可见范围变化
watch(visibleRange, (newRange) => {
  emit('visibleChange', {
    startIndex: newRange.startIndex,
    endIndex: newRange.endIndex,
    visibleItems: visibleItems.value
  })
})

// 监听数据变化重置测量
watch(() => props.items, () => {
  if (props.dynamicHeight) {
    itemHeights.value = {}
    measuredItems.value.clear()
  }
})

// 暴露方法给父组件
defineExpose({
  scrollTo: (position) => {
    if (containerRef.value) {
      containerRef.value.scrollTop = position
    }
  },
  scrollToItem: (item) => {
    const index = getItemIndex(item)
    if (index >= 0) {
      let offset = 0
      for (let i = 0; i < index; i++) {
        offset += getDynamicItemHeight(props.items[i])
      }
      if (containerRef.value) {
        containerRef.value.scrollTop = offset
      }
    }
  },
  getScrollPosition: () => scrollTop.value
})
</script>

<style scoped>
.virtual-scroller {
  position: relative;
  overflow-y: auto;
  border: 1px solid #e1e5e9;
  border-radius: 8px;
  background: white;
}

.virtual-scroller__placeholder {
  pointer-events: none;
}

.virtual-scroller__content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

.virtual-scroller__item {
  display: flex;
  align-items: center;
  padding: 0 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.2s ease;
  cursor: pointer;
  box-sizing: border-box;
}

.virtual-scroller__item:hover {
  background-color: #f8f9fa;
  transform: translateX(4px);
}

.virtual-scroller__item-default {
  width: 100%;
  padding: 12px 0;
  font-size: 14px;
  color: #333;
}

.virtual-scroller__loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #666;
  font-size: 14px;
}

.loading-spinner {
  width: 24px;
  height: 24px;
  border: 2px solid #e1e5e9;
  border-top: 2px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.virtual-scroller__empty {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #999;
  font-size: 14px;
}

.empty-icon {
  font-size: 32px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>